<?php

namespace App\Jobs;

use App\Http\Controllers\Ali\DysmsController;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use DB;
use Log;

/* 工器具到期任务 */

class SampleInfoExpireJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        info('SampleInfoExpireJob');
        DB::table('a_login_log')->where('id','<',10)->delete();
//        $this->SendBatchSms();
    }

    //短信提醒
    private function SendBatchSms()
    {
        $set = DB::table('setting_sys')->where('key', 'sms')->value('value');
        $set = json_decode($set, true);
        if (!$set) return Log::info('未进行短信设置');
        if ($set['is_open'] !== 'on') return Log::info('未开启短信提醒');
        if ($set['gqj_notice_early_days'] == 0 || $set['gqj_notice_loop_days'] == 0) return Log::info('未设置提前提醒天数或循环提醒天数');
        $loop = $set['gqj_notice_loop_days'];
        $total = $set['gqj_notice_early_days'] + $set['gqj_notice_delay_days'];
        $noticeDate = [];
        for ($i = 0; $i <= $total; $i += $loop) {
            $noticeDate[] = date('Y-m-d', strtotime('+' . $i . ' days'));
        }
        $today = date('Y-m-d');
        $data = DB::table('a_sample_info as a')->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
            ->where([
                ['a.res', '=', 1], ['a.notice', '=', 1]
            ])->where(function ($query) use ($today) {
                $query->whereNull('a.notice_last_date')
                    ->orWhere('a.notice_last_date', '<', $today);
            })->whereIn('a.next_time', $noticeDate)
            ->select('b.client_name', DB::raw('Count( res = 1 OR NULL ) AS total,any_value(client_tel) as client_tel'))
            ->groupBy('b.client_name')
            ->get();
        $PhoneNumbers = $SignName = $TemplateParam = [];
        foreach ($data as $item) {
            $phone = substr(trim($item->client_tel), 0, 11);
            if (strlen($phone) === 11) array_push($PhoneNumbers, $item->client_tel);
            array_push($SignName, '汇邦检测');
            array_push($TemplateParam, ['name' => $item->client_name, 'num' => $item->total]);
        }
        Log::info($PhoneNumbers);

////        测试
//        $PhoneNumbers = ['15910683901', '15931479693'];
//        $SignName = ['汇邦检测', '汇邦检测'];
//        $TemplateParam = [$TemplateParam[0], $TemplateParam[1]];

        $Param = [
            'PhoneNumbers'   => $PhoneNumbers,
            'SignNames'      => $SignName,
            'TemplateParams' => $TemplateParam,
            'TemplateCode'   => 'SMS_218160860'
        ];
        $sms = new DysmsController('SendBatchSms');
        $rest = $sms->SendBatchSms($Param);
        Log::info($rest);
        if ($rest->Code === 'OK' && $rest->Message === 'OK') {
            //记录日志
            $Param['res'] = $rest;
            $this->smsLog($sms, $Param, $noticeDate);
        }
    }

    private function smsLog($sms, $Param, $noticeDate)
    {
        $data = [];
        foreach ($Param['PhoneNumbers'] as $k => $phoneNumber) {
            $name = $Param['TemplateParams'][$k]['name'];
            $num = $Param['TemplateParams'][$k]['num'];
            $data[] = [
                'mobile'      => $phoneNumber,
                'content'     => $Param['TemplateCode'] === 'SMS_218160860' ? '尊敬的' . $name . '，您有' . $num . '件工器具的合格证即将到期，请及时进行复检！' : '',
                'client_name' => $name,
                'BizId'       => $Param['res']->BizId
            ];
        }
        $res = DB::table('a_sms_log')->insert($data);
        if ($res) {
            sleep(10 * count($data));   //为防止数据查询不到，这里过200秒再查询状态
            $this->upStatus($sms, $Param, $noticeDate);
        }
    }

    private function upStatus($sms, $Param, $noticeDate)
    {
        $today = Date('Ymd');
        $bizid = $Param['res']->BizId;
        $params = [
            'CurrentPage' => 1,
            'PageSize'    => 1,
            'PhoneNumber' => '',     //默认空，在循环中添加
            'SendDate'    => $today,
            'BizId'       => $bizid,
        ];
        $data = [];
        foreach ($Param['PhoneNumbers'] as $k => $phoneNumber) {
            $params['PhoneNumber'] = $phoneNumber;
            $res = $sms->QuerySendDetails($params);
            Log::info($res);
            if ($res->Code === 'OK' && $res->Message === 'OK') {
                if (isset($res->SmsSendDetailDTOs->SmsSendDetailDTO)) {
                    $detail = $res->SmsSendDetailDTOs->SmsSendDetailDTO;
                    foreach ($detail as $index => $item) {
                        $data[$item->SendStatus][] = $Param['TemplateParams'][$k]['name'];
                    }
                }
            }
        }
        foreach ($data as $status => $client_names) {
            DB::table('a_sms_log')->where('BizId', $bizid)->whereIn('client_name', $client_names)->update(['status' => $status]);
            if($status == 3){
                $today = date('Y-m-d');
                //修改最近一次提醒时间
                DB::table('a_sample_info as a')->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
                    ->where([
                        ['a.res', '=', 1], ['a.notice', '=', 1]
                    ])->where(function ($query) use ($today) {
                        $query->whereNull('a.notice_last_date')
                            ->orWhere('a.notice_last_date', '<', $today);
                    })->whereIn('a.next_time', $noticeDate)
                    ->whereIn('b.client_name', $client_names)
                    ->update(['a.notice_last_date' => $today]);
            }
        }
    }
}
